import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Home, BannerType } from './home.entity';

// 分页响应接口
export interface PaginatedHomes {
  data: Home[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
}

@Injectable()
export class HomeService {
  constructor(
    @InjectRepository(Home)
    private homeRepository: Repository<Home>,
  ) { }

  // 创建轮播图
  async create(createData: {
    title: string;
    description?: string;
    images?: any;
    image_url?: string;
    link_url?: string;
    sort_order?: number;
    is_visible?: boolean;
  }): Promise<Home> {
    const home = this.homeRepository.create({
      ...createData,
      sort_order: createData.sort_order || 1,
      is_visible: createData.is_visible !== undefined ? createData.is_visible : true,
    });
    return this.homeRepository.save(home);
  }


  async update(
    id: number,
    updates: {
      title: string;
      description?: string;
      images?: any;  // 图片
      image_url?: string;  // 图片URL
      link_url?: string;
      sort_order?: number;
      is_visible?: boolean; // 是否显示
    },
    type: BannerType
  ): Promise<Home> {
    const page = await this.homeRepository.findOne({ where: { id, type } });
    if (!page) {
      throw new NotFoundException(`Category with ID ${id} not found`);
    }

    // 合并更新字段（保留未修改的原始值）
    const updateBanner = this.homeRepository.merge(page, updates);
    return this.homeRepository.save(updateBanner);
  }

  // 获取所有轮播图（后台管理用）
  async findAllByType(type: BannerType): Promise<Home[]> {
    return this.homeRepository.find({
      where: { type },
      order: { sort_order: 'DESC', created_at: 'DESC' },
    });
  }

  // 获取所有轮播图（分页，后台管理用）
  async findAllByTypePaginated(
    type: BannerType,
    page: number = 1,
    limit: number = 10,
  ): Promise<PaginatedHomes> {
    const [data, total] = await this.homeRepository.findAndCount({
      where: { type },
      order: { sort_order: 'DESC', created_at: 'DESC' },
      skip: (page - 1) * limit,
      take: limit,
    });

    const totalPages = Math.ceil(total / limit);

    return {
      data,
      meta: {
        total,
        page,
        limit,
        totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1,
      },
    };
  }


  // 删除设计页面（需检测关联数据）
  async delete(id: number, type: BannerType): Promise<void> {
    const result = await this.homeRepository.delete({ id, type });
    if (result.affected === 0) {
      throw new NotFoundException(`Banner with ID ${id} not found`);
    }
  }

  /**
 * 按类型查询可见的轮播图（前端展示用）
 */
  async findActiveByType(type: BannerType): Promise<Home[]> {
    return this.homeRepository.find({
      where: {
        type,
        is_visible: true // 只返回可见的
      },
      order: { sort_order: 'ASC' } // 按排序号升序
    });
  }

}
